/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-17 9:09:21
 ******************************************************************************/
package cn.cmcc.online.smsapi.sdk.net;

import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

import android.os.Process;

import cn.cmcc.online.smsapi.sdk.Iservice.XyCallBack;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.net.util.ServerUtil;
import cn.cmcc.online.smsapi.sdk.threadpool.SmartSmsThreadPoolManager;
import cn.cmcc.online.smsapi.sdk.util.FileUtils;
import cn.cmcc.online.smsapi.sdk.util.KeyManager;
/*SDK-616 hewengao/20160918 start*/
/*SDK-616 hewengao/20160918 end*/
public class NetWebUtil {
    public static String WEB_SERVER_URL2 = "http://android"
            + (int) (Math.random() * 2 + 1)
            + ".bizport.cn:9998/AndroidWeb/kbAction";
    public static String WEB_SERVER_URL = "http://android"
            + (int) (Math.random() * 2 + 1) + ".bizport.cn:9998/AndroidWeb/";
    public static String WEB_SERVER_URL_FLIGHT = "http://android.bizport.cn:9998/AndroidWeb/flightAction";
    public static String WEBACTIVITY_URL = "http://x.bizport.cn/get_url_red";

    public static String WEB_SERVER_URL_DISCOVER = "http://android.bizport.cn:9998/AndroidWeb/findservice";
    public static String WEB_SERVER_URL_MOVIE_POSTERS = "https://service.bizport.cn/commerce/movie/sdk/posterpath";
    public static String WEB_SERVER_URL_COMMING_MOVIE = "https://service.bizport.cn/commerce/movie/sdk/getMovieComming";

//    static ExecutorService netWebPool = Executors.newFixedThreadPool(2);
    /* SDK-597 songzhirong 20160824 start*/
    public static void executeRunnable(Runnable runnable) {
        /*SDK-616 hewengao 20160912 start*/
        SmartSmsThreadPoolManager.netWebPool.execute(runnable);
        /*SDK-616 hewengao 20160912 end*/
    }
    /* SDK-597 songzhirong 20160824 end*/

    public static void sendPostRequest(final String url,
            final String postParam, final XyCallBack callback) {
        /*SDK-616 hewengao 20160912 start*/
        SmartSmsThreadPoolManager.netWebPool.execute(new Runnable() {
        /*SDK-616 hewengao 20160912 start*/
            public void run() {
            	try {
                    /*SDK-616 hewengao 20160912 start*/
                    SmartSmsThreadPoolManager.setThreadNameAndPriority("xy-netWebPool", Process.THREAD_PRIORITY_BACKGROUND);
                    /*SDK-616 hewengao 20160912 end*/
            		sendPost(url, postParam, callback);
				} catch (Throwable e) {
					LogManager.e(Constant.TAG, e.getMessage(), e);
				}
            }
        });
    }

    private static String sendPost(String url, String param, XyCallBack callback) {
        PrintWriter out = null;
        InputStream in = null;
        String result = "";
        byte[] bt = null;
        try {
            KeyManager.initAppKey();
            URL realUrl = new URL(url);
            URLConnection conn;
            /*SDK-682 chenrong start*/
            if (url.toLowerCase().startsWith("https")) {
                conn = HttpConnection.createHttpsURLConnection(url);
            } else {
                conn = realUrl.openConnection();
            }
            /*SDK-682 chenrong end*/
            conn.setConnectTimeout(BaseHttpRunnable.timeoutConnection);// 设置连接超时时间
            conn.setReadTimeout(BaseHttpRunnable.readTimeout);// 设置读取时间超时
            conn.addRequestProperty("sdkversion", NetUtil.APPVERSION);// 客户端应用版本号
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("app_key", XyHttpRunnable.appKey);
            conn.addRequestProperty("p", BaseHttpRunnable.getDeviceId(true));
            /*SDK-552 hewengao start*/
            conn.addRequestProperty("x", ServerUtil.getSha256Xid());
            /*SDK-552 hewengao end*/
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // LogManager.e("NetWebUtil", "request : "+param);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = conn.getInputStream();
            bt = FileUtils.getInputStream(in);
            // bt= new byte[1024*2];
            // int len =0;
            // ByteArrayOutputStream bao = new ByteArrayOutputStream();
            // while((len=in.read(bt)) > 0){
            // bao.write(bt, 0, len);
            // }
            // bao.flush();
            // bt = bao.toByteArray();
            result = new String(bt, "UTF-8");
            // LogManager.e("NetWebUtil", "result: "+result);
            // bao.close();
            // bt= result.getBytes();
            callback.execute(new String[] { "0", result });
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "sendPost: ", e);

            callback.execute(new String[] { "-1", "error: " + e.getMessage() });
        } finally {
        	bt = null;
            try {
            	/*SDK-646 zhaojiangwei 20161122 start */
                if (in!=null) {
                	in.close();
				}
            	if (out!=null) {
            		out.close();
				}
            	/*SDK-646 zhaojiangwei 20161122 end */
            } catch (Throwable e) {
//                ex.printStackTrace();
                LogManager.e(Constant.TAG, "sendPost: ", e);
            }
        }
        return result;
    }

}
